package com.yjy.controller;
// Tomcat 10+ 写法

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.PageInfo;
import com.yjy.common.Result;
import com.yjy.entity.User;
import com.yjy.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    @GetMapping("/selectAll")
    public Result selectAll(){
        List<User> users = userService.selectAll(null);
        return Result.success(users);
    }

    @PostMapping("/add")
    public Result add(@RequestBody User user) {//@RequestBody 接受前端传来的json参数 get是接受不到json的 post delete put可以接受
        userService.add(user);
        return Result.success();
    }

    @PutMapping("/update")
    public Result update(@RequestBody User user) {//@RequestBody 接受前端传来的json参数 get是接受不到json的 post delete put可以接受
        userService.update(user);
        return Result.success();
    }

    @DeleteMapping ("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        userService.deleteById(id);
        return Result.success();
    }

    @DeleteMapping ("/deleteBatch")
    public Result deleteBatch(@RequestBody List<User>list) { //@RequestBody 接收前端传过来的json数组
        userService.deleteBatch(list);
        return Result.success();
    }



    /**
     * 分页查询
     * pageNum: 当前的页码
     * pageSize: 每页的个数
     */
    @GetMapping("/selectPage")
    public Result selectPage(@RequestParam(defaultValue = "1")Integer pageNum,
                             @RequestParam(defaultValue = "10")Integer pageSize,
                             User user)
    {
                             //@RequestParam(required = false)String name){//也可以User user
        PageInfo<User> userPageInfo = userService.selectPage(pageNum, pageSize,user);
        return Result.success(userPageInfo); //返回的是分页的对象
    }


    /**
     * 数据导出
     * @return
     */

//    @GetMapping("/export")
//    public ResponseEntity<Resource> exportData() throws Exception {
//        List<User> users = userService.selectAll();
//        ExcelWriter writer = ExcelUtil.getWriter(true);
//
//        // 设置中文表头
//        writer.addHeaderAlias("username", "账号");
//        writer.addHeaderAlias("name", "名称");
//        writer.addHeaderAlias("phone", "电话");
//        writer.addHeaderAlias("email", "邮箱");
//
//        // 将数据写入内存流
//        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//        writer.write(users);
//        writer.flush(outputStream);
//        writer.close();
//
//        // 构建响应体
//        ByteArrayResource resource = new ByteArrayResource(outputStream.toByteArray());
//        String fileName = URLEncoder.encode("管理员信息", StandardCharsets.UTF_8);
//
//        return ResponseEntity.ok()
//                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName + ".xlsx")
//                .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
//                .body((Resource) resource);
//    }

    /**
     *
     * @param user
     * @param ids 1 , 2 , 3
     * @param response
     * @throws Exception
     */
    @GetMapping("/export")
    public void exportData(User user,/*@RequestParam(required = false)String ids,*/HttpServletResponse response) throws Exception {
//        if(StrUtil.isBlank(ids)){
//            String[] arr = ids.split(",");
//        }
        String ids = user.getIds();
        if (StrUtil.isNotBlank(ids)) {
            String[] idsArr = ids.split(",");
            user.setIdsArr(idsArr);
        }
        //1.拿到所有的数据
        List<User> users = userService.selectAll(user);
        //2.构建Writer对象
        ExcelWriter writer = ExcelUtil.getWriter(true);//是Excel
        //3.设置中文表头
        writer.addHeaderAlias("username","账号");
        writer.addHeaderAlias("name","名称");
        writer.addHeaderAlias("phone","电话");
        writer.addHeaderAlias("email","邮箱");

        writer.setOnlyAlias(true);
        //4.写出数据到writer
        writer.write(users);
        //5.设置输出的文件的名称以及输出流的头信息
        String fileName = URLEncoder.encode("管理员信息", StandardCharsets.UTF_8);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName + ".xlsx");
        //6.写出到输出流并关闭writer
        ServletOutputStream os = response.getOutputStream();
        writer.flush(os);
        writer.close();
        os.close();

    }

    @PostMapping("/import")
    public Result importData(MultipartFile file) throws Exception {
        //1.拿到输入流,构建reader
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //2.通过Reader 获取excel里面的数据
        reader.addHeaderAlias("账号","username");
        reader.addHeaderAlias("名称","name");
        reader.addHeaderAlias("电话","phone");
        reader.addHeaderAlias("邮箱","email");

        //3.将数据读取到数据库
        List<User> list = reader.readAll(User.class);
        for (User user : list) {
            userService.add(user);
        }
        return Result.success();

    }
}
